package cn.topevery.garden.dal.logic.warning;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class WxMessageService {
    private static String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type={grant_type}&appid={appid}&secret={secret}";

    private static final Map<String, Object> uriVariables = new HashMap<String, Object>() {
        {
            put("grant_type", "client_credential");
            put("appid", "wxd09060865509b624");
            put("secret", "ad894bb3aef5260008c3fda7825b3c55");
        }
    };

    private static final Lock lock = new ReentrantLock();

    @Resource(name = "remoteRestTemplate")
    private RestTemplate restTemplate;

    public void sendTemplateMessage(Map<String, String> warningObj) {
        String accessToken = getAccessToken();
        List<String> userList = getUserList(accessToken);
        String templateMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        String templateId = "2Z2S9aavzWJpgQ7yF_nK8GsC11fB7R5TFbxQDVWarHA";
        Map<String, Object> messageMap = new HashMap<>();
        messageMap.put("template_id", templateId);//模板ID

        Map<String, String> miniprogram = new HashMap<>();//跳小程序所需数据，不需跳小程序可不用传该数据
        miniprogram.put("appid", "wx2e8172661ea123f6");
        miniprogram.put("page", "pages/code/index.html");
        messageMap.put("miniprogram", miniprogram);

        handleData(messageMap, warningObj);//处理模板中的自定义数据

        HttpHeaders httpHeaders = setHeaders();
        for (String userOpenId : userList) {
            new Thread(() -> {
                try {
                    lock.lock();
                    messageMap.put("touser", userOpenId);
                    log.info("消息参数：{}", messageMap);
                    HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(messageMap, httpHeaders);
                    ResponseEntity<String> response = restTemplate.exchange(templateMessageUrl, HttpMethod.POST, httpEntity, String.class);
                    log.info("response:{}", response);
                } catch (RestClientException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }).start();
        }
    }

    private void handleData(Map<String, Object> messageMap, Map<String, String> warningObj) {
        JSONObject data = new JSONObject();

        JSONObject first = new JSONObject();
        first.put("value", "尊敬的用户，您有新的工单待处理\n" + warningObj.get("first"));
        first.put("color", "#173177");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", warningObj.get("keyword1"));
        keyword1.put("color", "#173177");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", warningObj.get("keyword2"));
        keyword2.put("color", "#173177");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", warningObj.get("keyword3"));
        keyword3.put("color", "#173177");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", warningObj.get("keyword4"));
        keyword4.put("color", "#173177");

        JSONObject keyword5 = new JSONObject();
        keyword5.put("value", warningObj.get("keyword5"));
        keyword5.put("color", "#173177");

        JSONObject remark = new JSONObject();
        remark.put("value", "请点击查看详情");
        remark.put("color", "#173177");

        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);
        data.put("keyword3", keyword3);
        data.put("keyword4", keyword4);
        data.put("keyword5", keyword5);
        data.put("remark", remark);

        messageMap.put("data", data);
    }

    public String getAccessToken() {
        String response = restTemplate.getForObject(accessTokenUrl, String.class, uriVariables);
        Map map = JSON.parseObject(response, Map.class);
        log.info("access_token:{}", map.get("access_token"));
        return map.get("access_token").toString();
    }

    public List<String> getUserList(String accessToken) {
        String getUserUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={accessToken}";
        Map<String, Object> uriVariables = new HashMap<String, Object>() {
            {
                put("accessToken", accessToken);
            }
        };
        String response = restTemplate.getForObject(getUserUrl, String.class, uriVariables);
        Map map = JSON.parseObject(response, Map.class);
        Map<String, List<String>> data = JSONObject.parseObject(map.get("data").toString(), new TypeReference<Map<String, List<String>>>() {
        });
        return data.get("openid");
    }

    private HttpHeaders setHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        headers.add("Accept-Charset", "UTF-8");
        return headers;
    }

}
